package com.tangyanbo.android.FileManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.View;
import android.widget.EditText;
import com.tangyanbo.filemanager.common.compress.Compress;
import com.tangyanbo.filemanager.common.constant.DialogTextConstant;
import com.tangyanbo.filemanager.common.constant.FileOperateState;
import com.tangyanbo.filemanager.common.util.Util;
import com.tangyanbo.filemanager.icon.FileIcon;
import com.tangyanbo.filemanager.menu.FileOperateMenu;

public class FileManager {

	private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();

	private final File ROOT_DIR = new File("/");//Environment.getExternalStorageDirectory();
	
	private File currentDirectory = ROOT_DIR;

	private ListActivity context;
	
	private File copyFile;
	
	private FileOperateState fileOptState = FileOperateState.NONE;
	
	private TopPosition topPosition = new TopPosition();	
	
	private boolean editMode = false;
	
	private List<Integer> checkedPositions = new ArrayList<Integer>();

	private FileManager(ListActivity context){
		this.context = context;
	}

	private void openFile(File aFile) {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		File file = new File(aFile.getAbsolutePath());
		intent.setDataAndType(Uri.fromFile(file), MIMETYPE.getMIMEType(file.getName()));		
		context.startActivity(intent);
	}

	private void browseTo(final File file) {
		if (file.isDirectory()) {
			setListViewTitle(file.getAbsolutePath());
			setCurrentDirectory(file);
			File[] files = file.listFiles(new HiddenFileFilter());
			List<File> fileList = new ArrayList<File>();
			if(files!=null){
				fileList = new ArrayList<File>(Arrays.asList(files));
			}
			fill(fileList);
		} else {
			openFile(file);
		}
	}
	
	private void setCurrentDirectory(File file){
		currentDirectory = file;
	}
	
	private void setListViewTitle(String text){
		context.setTitle(text);
	}

	private void fill(List<File> files) {
		Util.sortFiles(files);
		directoryEntries = getDirectoryEntries(files);
		IconifiedTextListAdapter itla = new IconifiedTextListAdapter(context);
		itla.setListItems(directoryEntries);
		itla.setEditMode(editMode);
		context.setListAdapter(itla);
	}
	
	private void setFirstSelection(){
		context.setSelection(topPosition.getParent().getTopPosition());
	}	
	
	private void rename(final File file) {	
		final View dialogview = ViewManager.getRenameView(context);
		Builder builder = BuilderManager.makeRenameDialog(context,dialogview,file.getName());		
		builder.setPositiveButton(android.R.string.ok,
				new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String value = getFullFileName(getRenameFileText(dialogview));						
						if (new File(value).exists()) {
							Builder builder = BuilderManager.makeRenameFileNameIsExistDialog(context);
							builder.setPositiveButton(android.R.string.ok,
									new AlertDialog.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											String str2 = getFullFileName(getRenameFileText(dialogview));		
											file.renameTo(new File(str2));
											refresh();
										}
									});
							builder.show();
						} else {
							file.renameTo(new File(value));
							refresh();
						}
					}
				});
		builder.show();
	}
	
	private String getRenameFileText(View dialogview){
		return ((EditText)dialogview.findViewById(R.id.EditText01))
				.getText().toString();
	}
	
	private String getZIPFileText(View view){
		return ((EditText)view.findViewById(R.id.EditText_zip))
		.getText().toString();
	}
	
	

	private void delete(final File file) {
		Builder builder = BuilderManager.makeDeletePositiveOrCancelDialog(context, file.getName());
		builder.setPositiveButton(android.R.string.ok,
				new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (Util.deleteFile(file)) {
							Builder builder = BuilderManager.makeDeleteSuccessDialog(context);
							builder.setPositiveButton(android.R.string.ok,
									new AlertDialog.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
											refresh();
										}
									});
							builder.show();
						} else {
							Builder builder = BuilderManager.makeDeleteFailureDialog(context);
							builder.show();
						}
					}
				});
		builder.show();
	}
	
	
	
	
	private String getCurDirectory() {
		return currentDirectory.getAbsolutePath();
	}	
	
	private void copy(File file) {
		copyFile = file;
		fileOptState = FileOperateState.COPY;
	}
	
	private void cut(File file) {
		copyFile = file;
		fileOptState = FileOperateState.CUT;
	}
	
	private void moveFile(String source, String destination) {
		new File(source).renameTo(new File(destination));
	}	
	
	
	private boolean fileNameIsExistInCurrentDir(String fileName){
		return new File(getFullFileName(fileName))
		.exists();
	}
	
	
	private void zipOrUnZip(final File file){
		if(Util.isZIP(file.getName())){
			Builder builder = BuilderManager.makeUnZIPDialog(context);
			builder.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Compress.unZip(file, currentDirectory.getAbsolutePath());
							refresh();
						}
					});
			builder.show();
		}else{
			final View zipview = ViewManager.getZIPView(context);
			Builder builder = BuilderManager.makeZIPDialog(context,zipview,file.getName());		
			builder.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Compress.zip(file, new File(getFullFileName(getZIPFileText(zipview))));
							refresh();
						}
					});
			builder.show();
		}
	}
	
	
	public void fileOptMenu(final File file) {
		OnClickListener listener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {				
				case FileOperateMenu.RENAME:
					rename(file);
					break;
				case FileOperateMenu.DELETE:
					delete(file);
					break;
				case FileOperateMenu.COPY:
					copy(file);
					break;
				case FileOperateMenu.CUT:
					cut(file);
					break;
				case FileOperateMenu.ZIP:
					zipOrUnZip(file);
					break;
				}
			}
		};
		new AlertDialog.Builder(context).setTitle(DialogTextConstant.FILE_OPT_TITLE)
				.setItems(FileOperateMenu.getMenuItems(Util.isZIP(file.getName())), listener).show();
	}
	
	
	public void browseToCurrent(){
		browseTo(currentDirectory);
	}
	
	public String getFullFileName(String fileSimpleName){
		return getCurDirectory() + "/" + fileSimpleName;
	}
	
	public String getListItemTextByPosition(int position){
		return directoryEntries.get(position).getText();
	}
	
	public void refresh() {
		browseTo(currentDirectory);
	}
	
	public static FileManager getFileManager(FileActivity context) {
		return new FileManager(context);
	}			

	public List<IconifiedText> getDirectoryEntries(List<File> files) {
		List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
		Drawable currentIcon = null;
		for (File currentFile : files) {
			FileIcon fileIcon = new FileIcon(context);
			if (currentFile.isDirectory()) {
				currentIcon = fileIcon.getFolderIcon();
			} else if(Util.getFileEndingByFileName(currentFile.getName()).equals(".apk")){
				currentIcon = fileIcon.getApkFileIcon(currentFile.getPath());
			}else{
				currentIcon = fileIcon.getIconByFileEnding(Util
						.getFileEndingByFileName(currentFile.getName()));
			}
			directoryEntries.add(new IconifiedText(currentFile.getName(), currentIcon));
		}
		return directoryEntries;
	}

	public void browseToRoot() {
		browseTo(ROOT_DIR);
	}
	
	public void upOneLevel() {		
		if(editMode){
			editMode = false;
			setTopPosition();
			refresh();
			setFirstSelection();
			return;
		}
		
		if (!currentDirectory.getPath().equals(ROOT_DIR.getPath())){
			currentDirectory = new File(currentDirectory.getParent());
			browseTo(currentDirectory);
			setFirstSelection();
			return;
		}
		
		context.finish();
	}	
	
	public void Mynew() {
		final View dialogview = ViewManager.getDialogView(context);
		Builder builder = BuilderManager.makeNewFileDialog(context,dialogview);
		builder.setPositiveButton(android.R.string.ok,
				new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String value = ((EditText) dialogview
								.findViewById(R.id.EditText_PROM)).getText()
								.toString();
						File dirFile = new File(getFullFileName(value));
						if (Util.newFolder(dirFile)) {							
							Builder builder = BuilderManager.makeNewSuccessDialog(context);
							builder.setPositiveButton(android.R.string.ok,
									new AlertDialog.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
											refresh();
										}
									});
							builder.show();
						} else {
							Builder builder = BuilderManager.makeNewFailDialog(context);
							builder.show();
						}
					}
				});
		builder.show();
	}
	
	public void openFolder(int position) {
		File clickedFile = new File(getFullFileName(getListItemTextByPosition(position)));
		if (clickedFile != null){			
			this.browseTo(clickedFile);
		}			
	}
	
	public void MyDelete() {
		boolean success = true;
		for(int position : checkedPositions){
			String text = getListItemTextByPosition(position);
			File deleteFile = new File(this.getFullFileName(text));		
			if (!Util.deleteFolder(deleteFile)) {
				success = false;
				break;
			}
		}		
		if(success){
			Builder builder = BuilderManager.makeDeleteSuccessDialog(context);
			builder.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							editMode = false;
							setTopPosition();
							refresh();
							setFirstSelection();
						}
					});
			builder.show();			
		}else{
			Builder builder = BuilderManager.makeDeleteFailureDialog(context);
			builder.show();
		}
		checkedPositions.clear();
	}
	
	public void MyPaste() {
		if (copyFile == null) {
			BuilderManager.makePasteNoCopyOrCutDialog(context);
		} else {
			if (fileOptState == FileOperateState.COPY)
			{
				if (fileNameIsExistInCurrentDir(copyFile.getName())) {
					Builder builder = BuilderManager.makePasteExistSameFileNameDialog(context);				
					builder.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Util.copyFile(copyFile,
											new File(getFullFileName(copyFile.getName())));
									browseTo(new File(getCurDirectory()));
								}
							});
					builder.show();
				} else {
					Util.copyFile(copyFile, new File(getFullFileName(copyFile.getName())));
					refresh();
				}
			} else if (fileOptState == FileOperateState.CUT)
			{
				if (fileNameIsExistInCurrentDir(copyFile.getName())) {
					Builder builder = BuilderManager.makePasteExistSameFileNameDialog(context);
					builder.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									moveFile(
											copyFile.getAbsolutePath(),
											getFullFileName(copyFile.getName()));
									refresh();
								}
							});
					builder.show();
				} else {
					moveFile(copyFile.getAbsolutePath(), getFullFileName(copyFile.getName()));
					refresh();
				}
			}
		}
	}
	
	public void setTopPosition(){
		topPosition.setTopPosition(context.getListView().getFirstVisiblePosition());
		TopPosition child = new TopPosition();
		child.setParent(topPosition);
		topPosition = child;
	}

	
	
	public void edit(){
		checkedPositions.clear();
		editMode = true;
		setTopPosition();
		refresh();		
		setFirstSelection();
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}
	
	public void checkedFile(View v,int position){
		IconTextViewHolder holder = (IconTextViewHolder) v.getTag();
		if(holder.checkBox.isChecked()){
			holder.checkBox.setChecked(false);
			checkedPositions.remove(new Integer(position));
			directoryEntries.get(position).setChecked(false);
		}else{
			holder.checkBox.setChecked(true);
			checkedPositions.add(new Integer(position));
			directoryEntries.get(position).setChecked(true);
		}		
	}	
	
	
}
